package oss

import (
	times "gitee.com/magein/go-utils/time"
	tools "gitee.com/magein/go-utils/tool"
	"os"
	"strings"
)

// FileExtension Get file extension
func FileExtension(filename string) string {
	index := strings.LastIndex(filename, ".")
	var extension string
	if index == -1 {
		extension = ""
	} else {
		extension = filename[index+1:]
	}
	return strings.ToLower(extension)
}

// FileInfo Find information about the file
type FileInfo struct {
	Path        string
	Name        string
	Extension   string
	Size        int
	SizeFormat  string
	Mode        string
	ModTime     string
	ModUnixTime int64
}

// SearchFileSetting Search find setting
type SearchFileSetting struct {
	Path      string
	MinSize   int
	MaxSize   int
	Extension interface{}
}

func (setting SearchFileSetting) getExtension() []string {
	var extensions []string
	if ext, ok := setting.Extension.(string); ok {
		for _, val := range strings.Split(ext, ",") {
			extensions = append(extensions, val)
		}
		return extensions
	}
	if ext, ok := setting.Extension.([]string); ok {
		for _, val := range ext {
			extensions = append(extensions, val)
		}
	}
	return extensions
}

// SearchFile search file
func SearchFile(setting SearchFileSetting, list *[]FileInfo) {

	path := setting.Path
	extensions := setting.getExtension()

	fs, _ := os.OpenFile(path, os.O_RDONLY, os.ModeDir)

	files, _ := fs.Readdir(-1)

	for _, file := range files {

		if file.IsDir() {
			setting.Path = path + "/" + file.Name()
			SearchFile(setting, list)
		} else {

			minSize := int64(setting.MinSize)
			if minSize > 0 && file.Size() < minSize {
				continue
			}

			maxSize := int64(setting.MaxSize)
			if maxSize > 0 && file.Size() > maxSize {
				continue
			}
			extension := FileExtension(file.Name())
			if len(extensions) > 0 && !tools.InArray(extensions, FileExtension(file.Name())) {
				continue
			}

			res := FileInfo{
				Path:        setting.Path,
				Name:        file.Name(),
				Extension:   extension,
				Size:        int(file.Size()),
				SizeFormat:  tools.ConvertByte(file.Size()),
				Mode:        file.Mode().String(),
				ModTime:     times.Parse(file.ModTime()).DateTime(),
				ModUnixTime: file.ModTime().Unix(),
			}

			*list = append(*list, res)
		}
	}
}
